<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Expense extends CI_Model {

    public function add($expense) {
        $this->db->insert('expenses', $expense);
    }

    public function get_today($user_id) {
        $today = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
        $date = date("Y-m-d", $today);
        
        $sql = "SELECT SUM(amount) AS `sum` FROM `expenses` WHERE `expenses`.`user_id` = $user_id AND DATE(`expenses`.`timestamp`) = '$date';";
        $query = $this->db->query($sql);
        $result = $query->row_array();

        $sum = 0;

        if (isset($result['sum'])) {
            $sum = $result['sum'];
        }

        return $sum;
    }

    public function get_total($user_id) {
        $sql = "SELECT SUM(amount) AS `sum` FROM `expenses` WHERE `expenses`.`user_id` = $user_id;";
        $query = $this->db->query($sql);
        $result = $query->row_array();

        $sum = 0;

        if (isset($result['sum'])) {
            $sum = $result['sum'];
        }

        return $sum;
    }

    public function get($user_id, $offset) {
        $this->db->select('name, amount, unix_timestamp(timestamp) as timestamp');
        $this->db->from('expenses');
        $this->db->like('user_id', $user_id);
        $this->db->order_by('timestamp', 'desc');

        $query = $this->db->get('', 10, $offset);

        $expenses = $query->result_array();

        foreach ($expenses as &$expense) {
            $timestamp = $expense['timestamp'];
            $expense['timestamp'] = $this->time_since($timestamp) . ' ago';
        }

        return $expenses;
    }

    public function count_all($user_id) {
        $this->db->select('*');
        $this->db->from('expenses');
        $this->db->like('user_id', $user_id);
        $this->db->order_by('timestamp', 'desc');

        $count = $this->db->count_all_results();

        return $count;
    }

    public function summary($user_id) {
        $summary = array();
        
        for ($i = 6; $i >= 0; --$i) {
            $day = mktime(0, 0, 0, date("m"), date("d") - $i, date("Y"));
            $date = date("Y-m-d", $day);

            $this->db->select('SUM(amount) / 1000 AS sum');
            $this->db->from('expenses');
            $this->db->where('user_id', $user_id);
            $this->db->where('DATE(timestamp) = ' . '\'' . $date . '\'');
            $query = $this->db->get('');
            $result = $query->row_array();

            $sum = 0;

            if (isset($result['sum'])) {
                $sum = $result['sum'];
            }
            
            $key = date("M j", $day);
        
            $summary[$key] = $sum;
        }

        return $summary;
    }

    public function get_latest() {
        $this->db->select('`users`.`id`, `users`.`name`, `expenses`.`name` AS `item`, `expenses`.`amount`, unix_timestamp(`expenses`.`timestamp`) AS `timestamp`');
        $this->db->from('expenses');
        $this->db->join('users', 'expenses.user_id = users.id');
        $this->db->order_by('timestamp', 'desc');
        $query = $this->db->get('', 10);

        $expenses = $query->result_array();

        foreach ($expenses as &$expense) {
            $timestamp = $expense['timestamp'];
            $expense['timestamp'] = $this->time_since($timestamp) . ' ago';
        }

        return $expenses;
    }

    private function time_since($original) {
        // array of time period chunks
        $chunks = array(
            array(60 * 60 * 24 * 365, 'year'),
            array(60 * 60 * 24 * 30, 'month'),
            array(60 * 60 * 24 * 7, 'week'),
            array(60 * 60 * 24, 'day'),
            array(60 * 60, 'hour'),
            array(60, 'minute'),
        );

        $today = time(); /* Current unix time  */

        $since = $today - $original;

        // $j saves performing the count function each time around the loop
        for ($i = 0, $j = count($chunks); $i < $j; $i++) {

            $seconds = $chunks[$i][0];
            $name = $chunks[$i][1];

            // finding the biggest chunk (if the chunk fits, break)
            if (($count = floor($since / $seconds)) != 0) {
                // DEBUG print "<!-- It's $name -->\n";
                break;
            }
        }

        $print = ($count == 1) ? '1 ' . $name : "$count {$name}s";

        return $print;
    }

}
